<template>
    <div class="procure-management">
        <!-- 筛选表单 -->
        <el-card class="filter-card">
            <el-form :inline="true" class="filter-form">
                <!-- 采购单号筛选 -->
                <el-form-item label="采购单号：" prop="procure_number">
                    <el-input
                        v-model="filter.searchProcureId"
                        placeholder="请输入采购单号"
                        clearable
                        @keyup.enter="handleFilter"
                    />
                </el-form-item>

                <!-- 状态筛选 -->
                <el-form-item label="订单状态：" prop="procure_tag">
                    <el-select
                        v-model="filter.searchStatus"
                        placeholder="请选择状态"
                        clearable
                    >
                        <el-option label="全部" value=""></el-option>
                        <el-option
                            v-for="(label, key) in statusMap"
                            :key="key"
                            :label="label"
                            :value="Number(key)"
                        />
                    </el-select>
                </el-form-item>

                <!-- 操作按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="handleFilter" :loading="loading">查询</el-button>
                    <el-button @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 采购单列表 -->
        <el-card class="table-card">
            <!-- 数据表格 -->
            <el-table
                :data="procureList"
                border
                stripe
                style="width: 100%"
                v-loading="loading"
                :row-class-name="getRowClass"
            >
                <!-- 采购单号 -->
                <el-table-column
                    prop="procure_number"
                    label="采购单号"
                    width="180"
                    show-overflow-tooltip
                >
                    <template #default="{ row }">
                        <span>{{ row.procureNumber }}</span>
                    </template>
                </el-table-column>

                <!-- 采购日期 -->
                <el-table-column label="采购日期" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.procureTime) }}
                    </template>
                </el-table-column>

                <!-- 订单状态 -->
                <el-table-column label="订单状态" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.procureTag)" effect="dark">
                            {{ statusMap[row.procureTag] || "未知状态" }}
                        </el-tag>
                    </template>
                </el-table-column>

                <!-- 总金额 -->
                <el-table-column label="总金额" width="120" align="right">
                    <template #default="{ row }">
                        <span>￥{{ (row.procurePrice || 0).toFixed(2) }}</span>
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                        <el-button
                            type="primary"
                            size="small"
                            @click="showOrderDetail(row)"
                            :loading="row.id === currentLoadingId"
                        >查看明细</el-button>
                        <el-button
                            v-if="row.procureTag === 1"
                            type="success"
                            size="small"
                            @click="handleShip(row)"
                            :loading="row.id === shippingId"
                        >确认发货</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination
                class="pagination"
                v-model:current-page="current"
                v-model:page-size="pageSize"
                :page-sizes="pageList"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            />
        </el-card>

        <!-- 采购明细抽屉 -->
        <el-drawer
            :visible.sync="detailVisible"
            title="采购明细详情"
            direction="rtl"
            size="50%"
            @close="handleDrawerClose"
        >
            <div v-loading="detailLoading" class="detail-wrapper">
                <!-- 基础信息 -->
                <el-descriptions :column="1" border>
                    <!-- 采购单号 -->
                    <el-descriptions-item label="采购单号">
                        {{ currentProcure ? currentProcure.procureNumber : "--" }}
                    </el-descriptions-item>

                    <!-- 采购时间 -->
                    <el-descriptions-item label="采购时间">
                        {{ currentProcure ? formatDateTime(currentProcure.procureTime) : "--" }}
                    </el-descriptions-item>

                    <!-- 订单状态 -->
                    <el-descriptions-item label="订单状态">
                        <el-tag :type="getStatusType(currentProcure ? currentProcure.procureTag : null)">
                            {{ currentProcure ? statusMap[currentProcure.procureTag] : "--" }}
                        </el-tag>
                    </el-descriptions-item>

<!--                    &lt;!&ndash; 审核信息 &ndash;&gt;-->
<!--                    <el-descriptions-item label="审核状态">-->
<!--                        <div class="check-status">-->
<!--                            <el-tag :type="getCheckTagType(currentProcure ? currentProcure.checkTag : null)">-->
<!--                                {{ currentProcure ? checkStatusMap[currentProcure.checkTag] : "未审核" }}-->
<!--                            </el-tag>-->
<!--                            <span v-if="currentProcure && currentProcure.checkTime" class="check-time">-->
<!--                            ({{ formatDateTime(currentProcure.checkTime) }})-->
<!--                        </span>-->
<!--                        </div>-->
<!--                    </el-descriptions-item>-->
                </el-descriptions>

                <!-- 商品明细表格 -->
                <div class="detail-table">
                    <el-table
                        :data="procureDetails"
                        border
                        empty-text="暂无明细数据"
                        :row-class-name="getRowClass"
                        height="400"
                    >
                        <!-- 商品编号 -->
                        <el-table-column
                            prop="productId"
                            label="商品编号"
                            width="180"
                            show-overflow-tooltip
                        />

                        <!-- 商品名称 -->
                        <el-table-column
                            label="商品名称"
                            width="180"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span>{{scope.row.products[0].name}}</span>
                            </template>
                        </el-table-column>

                        <!-- 数量 -->
                        <el-table-column
                            prop="count"
                            label="数量"
                            width="100"
                            align="right"
                        />

                        <!-- 单价 -->
                        <el-table-column
                            label="单价"
                            width="120"
                            align="right"
                        >
                            <template #default="{ row }">
                                <span>￥{{ (row.price || 0).toFixed(2) }}</span>
                            </template>
                        </el-table-column>

                        <!-- 小计 -->
                        <el-table-column
                            label="小计"
                            width="120"
                            align="right"
                        >
                            <template #default="{ row }">
                                <span>￥{{ (row.subtotal || 0).toFixed(2) }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 金额汇总 -->
                <div class="total-section">
                    <div class="total-item">
                        <span class="label">采购总量：</span>
                        <span class="value">{{ currentProcure ? currentProcure.procureCount : 0 }}</span>
                    </div>
                    <div class="total-item">
                        <span class="label">采购总额：</span>
                        <span class="value amount">
                        ￥{{ (currentProcure ? currentProcure.procurePrice : 0).toFixed(2) }}
                    </span>
                    </div>
                </div>

                <!-- 发货操作按钮 -->
                <div class="action-buttons" v-if="currentProcure && currentProcure.procureTag === 1">
                    <el-button
                        type="success"
                        size="medium"
                        @click="handleShip(currentProcure)"
                        :loading="currentProcure.id === shippingId"
                    >
                        确认发货
                    </el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script>
// 导入工具函数
import { formatDateTime } from "@/utils/date";

/**
 * 采购管理页面组件
 * 功能：
 * 1. 展示采购单列表（分页+筛选）
 * 2. 查看采购明细详情
 * 3. 显示审核状态
 * 4. 响应式布局支持
 * 5. 待发货订单可以修改状态进行发货
 */
export default {
    name: "SuppliersOrderInfo",
    data() {
        return {
            detailVisible: false, // 控制详情抽屉的显示

            // 加载状态控制
            loading: false, // 主列表加载
            detailLoading: false, // 详情加载
            currentLoadingId: null, // 当前正在加载的采购单ID
            shippingId: null, // 当前正在发货的采购单ID

            // 筛选条件
            filter: {
                searchProcureId: "", // 采购单号筛选
                searchStatus: null, // 状态筛选
            },

            // 分页配置
            current: 1,
            pageSize: 10,
            pageList: [5, 10, 15, 20],
            total: 0,
            vo:{},

            // 数据存储
            procureList: [], // 采购单列表数据
            currentProcure: null, // 当前查看的采购单详情
            procureDetails: [], // 采购明细数据

            // 状态映射配置
            statusMap: {
                1: "待发货",
                2: "待收货",
                3: "已完成",
            },

            // 供应商信息
            currentSupplier: { suppliers: null },

            sid:0,
        };
    },

    mounted() {
        // 组件挂载时自动加载第一页数据
        this.fetchProcureList();
        // this.loadSupplierInfo()
    },

    methods: {
        // // 加载供货商信息
        // async loadSupplierInfo() {
        //     try {
        //         const user = JSON.parse(sessionStorage.getItem('user')) || {}
        //         const { data } = await this.$axios.post(`login/selectIdSuppliers/${user.id}`)
        //         this.currentSupplier = data || { suppliers: null }
        //         this.sid = this.currentSupplier.suppliers.supplierId
        //         console.log(666,this.sid)
        //     } catch (error) {
        //         console.error('加载供应商信息失败:', error)
        //         this.$message.error('加载供应商信息失败')
        //     }
        // },

        /**
         * 获取采购单列表数据
         */
        async fetchProcureList() {
            this.loading = true;
            try {
                const user = JSON.parse(sessionStorage.getItem('user')) || {}
                const { data } = await this.$axios.post(`login/selectIdSuppliers/${user.id}`)
                this.currentSupplier = data || { suppliers: null }
                this.sid = this.currentSupplier.suppliers.supplierId


                this.$axios.post(`procure/queryProcure/${this.current}/${this.pageSize}/${this.sid}`,this.vo).then(response =>{
                    if (response.data) {
                        this.procureList = response.data.list || [];
                        console.log(666,this.procureList)
                        this.total = response.data.total || 0;
                    } else {
                        this.$message.error('获取采购单列表失败');
                    }
                })


            } catch (error) {
                console.error('获取采购单列表异常:', error);
                this.$message.error('获取采购单列表失败');
            } finally {
                this.loading = false;
            }
        },

        /**
         * 查看采购单明细
         * @param {Object} row 当前行数据
         */
        async showOrderDetail(row) {
            this.detailLoading = true;
            this.currentLoadingId = row.id;
            this.detailVisible = true;

            try {
                // 获取主数据
                this.currentProcure = { ...row };

                // 获取明细数据
                const response = await this.$axios.get(`procure/selectDetails/${row.id}`);
                console.log(333,response.data)
                this.procureDetails = response.data || [];
            } catch (error) {
                console.error("详情加载异常:", error);
                this.$message.error("详情数据加载失败");
            } finally {
                this.detailLoading = false;
                this.currentLoadingId = null;
            }
        },

        /**
         * 处理发货操作
         * @param {Object} order 订单数据
         */
        async handleShip(order) {
            try {
                await this.$confirm('确认要将该订单状态改为"待收货"吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                this.shippingId = order.id;

                // 调用API更新订单状态
               this.$axios.post(`procure/updateStatus/${order.id}`).then( response=>{
                       this.$message.success('发货成功');


                   // 1. 更新当前订单状态
                   if (this.currentProcure && this.currentProcure.id === order.id) {
                       this.currentProcure.procureTag = 2; // 更新为待收货状态
                   }

                   // 2. 更新列表中的订单状态
                   this.procureList = this.procureList.map(item => {
                       if (item.id === order.id) {
                           return { ...item, procureTag: 2 };
                       }
                       return item;
                   });

                   // 3. 如果详情抽屉打开，强制更新视图
                   if (this.detailVisible) {
                       this.$forceUpdate();
                   }
                   // 刷新列表数据
                   this.fetchProcureList();
               })
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('发货操作异常:', error);
                    this.$message.error('发货操作失败');
                }
            } finally {
                this.shippingId = null;
            }
        },

        /**
         * 处理分页大小变化
         * @param {number} newSize 新分页大小
         */
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.current = 1; // 重置到第一页
            this.fetchProcureList();
        },

        /**
         * 处理页码变化
         * @param {number} newPage 新页码
         */
        handlePageChange(newPage) {
            this.current = newPage;
            this.fetchProcureList();
        },

        /**
         * 执行筛选查询
         */
        handleFilter() {
            this.current = 1; // 重置到第一页
            this.vo = this.filter
            this.fetchProcureList();
        },

        /**
         * 重置筛选条件
         */
        resetFilter() {
            this.filter = {
                procure_number: "",
                procure_tag: null,
            };
            this.handleFilter();
        },

        /**
         * 获取状态标签类型
         * @param {number} status 状态码
         * @returns {string} element标签类型
         */
        getStatusType(status) {
            if (!status && status !== 0) return "info";
            const typeMap = {
                1: "warning", // 待发货-橙色
                2: "primary", // 待收货-蓝色
                3: "success", // 已完成-绿色
            };
            return typeMap[status] || "info";
        },


        /**
         * 格式化日期时间
         * @param {string} date 原始日期字符串
         * @returns {string} 格式化后的日期
         */
        formatDateTime(date) {
            return date ? formatDateTime(date) : "--";
        },

        /**
         * 根据订单状态设置行的类名
         * @param {Object} rowInfo 行信息
         * @returns {string} 类名
         */
        getRowClass({ row }) {
            const status = row.procure_tag;
            if (status === 1) {
                return 'status-waiting-delivery';
            } else if (status === 2) {
                return 'status-waiting-receipt';
            } else if (status === 3) {
                return 'status-completed';
            }
            return '';
        },
        handleDrawerClose(done) {
            if (this.detailLoading) {
                this.$message.warning('数据正在加载中，请稍候');
                return false;
            }
            done();
        },
    },
};
</script>

<style lang="scss" scoped>
.procure-management {
    padding: 20px;
    background: #f0f2f5;
    min-height: calc(100vh - 40px);

    // 筛选卡片样式
    .filter-card {
        margin-bottom: 20px;

        :deep(.el-card__body) {
            padding: 18px 20px;
        }
    }

    // 表格卡片样式
    .table-card {
        :deep(.el-card__body) {
            padding: 0;
        }

        .operation-bar {
            padding: 16px;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }

    // 分页样式
    .pagination {
        padding: 16px;
        display: flex;
        justify-content: flex-end;
    }

    // 详情抽屉样式
    .detail-wrapper {
        padding: 20px;
        height: 100%;
        display: flex;
        flex-direction: column;

        .check-status {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .check-time {
            color: #909399;
            font-size: 12px;
        }

        .detail-table {
            margin: 20px 0;
            flex: 1;
            overflow: hidden;
        }

        .total-section {
            padding: 16px;
            background: #f8f9fa;
            border-radius: 4px;
            margin-top: auto;

            .total-item {
                display: flex;
                justify-content: flex-end;
                margin-bottom: 8px;
                font-size: 14px;

                .label {
                    color: #606266;
                    margin-right: 12px;
                }

                .value {
                    color: #303133;
                    min-width: 100px;
                    text-align: right;

                    &.amount {
                        color: #f56c6c;
                        font-weight: bold;
                        font-size: 16px;
                    }
                }
            }
        }

        .action-buttons {
            margin-top: 20px;
            text-align: right;
            padding-top: 16px;
            border-top: 1px solid #ebeef5;
        }
    }

    // 表格边框样式
    :deep(.el-table) {
        border: 1px solid #ebeef5;

        th,
        td {
            border-right: 1px solid #ebeef5;
        }

        th:last-child,
        td:last-child {
            border-right: none;
        }
    }

    // 根据订单状态设置行的背景颜色
    :deep(.status-waiting-delivery) {
        background-color: #fff6e5;
    }

    :deep(.status-waiting-receipt) {
        background-color: #e5f6ff;
    }

    :deep(.status-completed) {
        background-color: #e5ffe5;
    }
}

// 移动端适配
@media screen and (max-width: 768px) {
    .procure-management {
        padding: 12px;

        .filter-form {
            .el-form-item {
                margin-right: 8px;
                margin-bottom: 8px;
            }
        }

        :deep(.el-drawer) {
            width: 90% !important;
        }
    }
}
</style>